package com.carleasoft.mps.file.controller;

import com.alibaba.fastjson.JSON;

import com.carleasoft.mps.file.bean.po.EditorPo;
import com.carleasoft.mps.file.bean.vo.FileUploadVo;
import com.carleasoft.mps.file.common.util.JsonConfig;
import com.carleasoft.mps.file.service.FileManageService;
import com.carleasoft.mps.utils.MinioUtils;
import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MinioClient;
import io.minio.http.Method;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program:
 * @description:
 * @author: ztm
 * @create: 2019/12/27 8:47
 **/

@RestController
@RequestMapping(value = "/file")
public class EditorController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private FileManageService fileService;
    @Autowired
    private MinioUtils minioUtils;

    @Value("${full-path}")
    private String fullPath;




    @RequestMapping(value = "/exec", method = {RequestMethod.GET})
    public void exec(EditorPo editorPo, HttpServletResponse httpServletResponse) throws Exception {
        this.config(editorPo, httpServletResponse);
    }

    @RequestMapping(value = "/exec", method = {RequestMethod.POST})
    public void execpost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        this.ueditorUpload(httpServletRequest, httpServletResponse);
    }

    public void config(EditorPo editorPo, HttpServletResponse httpServletResponse) throws Exception {

        String returnurl = JsonConfig.ResolveJsonFileToString("config.json");
        if (StringUtils.isNotEmpty(editorPo.getCallback())) returnurl = editorPo.getCallback() + "(" + returnurl + ")";
        httpServletResponse.setContentType("text/html; charset=utf-8");
        httpServletResponse.setHeader("Access-control-Allow-Origin", "*");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "*");
//        httpServletResponse.setHeader("Vary","Accept-Encoding");
//        httpServletResponse.setHeader("Content-Encoding","gzip");
//        httpServletResponse.setHeader("Connection ","keep-alive");
        httpServletResponse.setStatus(HttpStatus.OK.value());
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        outputStream.write(returnurl.getBytes());
        outputStream.flush();
    }

    public void ueditorUpload(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) httpServletRequest;

        MultipartFile file = multipartRequest.getFile("upfile");
        String suffix = this.getSuffix(file.getOriginalFilename());
        FileUploadVo fileUploadVo = fileService.upload(file);
        List<String> upload = minioUtils.upload(new MultipartFile[]{file});
        Map urlMap = new HashMap<String, String>();
        urlMap.put("url", fileUploadVo.getFilePath());

        urlMap.put("state", "SUCCESS");
        urlMap.put("original", upload.get(0));
        urlMap.put("size", file.getSize());
        urlMap.put("title", upload.get(0));
        urlMap.put("type", suffix);
        httpServletResponse.setContentType("application/json; charset=utf-8");
        httpServletResponse.setHeader("Access-control-Allow-Origin", "*");
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");

        PrintWriter out = null;
        try {
            out = httpServletResponse.getWriter();
            out.append(JSON.toJSONString(urlMap));
        } catch (IOException e) {
            logger.error("返回Response信息出现IOException异常:" + e.getMessage());
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    /**
     * 截取文件后缀名
     *
     * @param originalFilename
     * @return String
     */
    private String getSuffix(String originalFilename) {
        String suffix = "";
        int i = originalFilename.indexOf(".");
        if (i != -1) {
            String[] str = originalFilename.split("\\.");
            suffix = str[1];
        }
        return suffix;
    }
}
